package com.yingpai.fitness.dvp_2_0.main.fragment.fitness;

import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.fragment.CommonFragment;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.common.view.XGridView;
import com.yingpai.fitness.dvp_2_0.common.view.XListView;
import com.yingpai.fitness.dvp_2_0.main.activity.WebViewForBannerActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.fitness.FitnessStrategyActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.fitness.RecreationActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.fitness.RunRideTopicDetailActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.fitness.StepDetailActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.fitness.StoreActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.vip.VipCardActivity;
import com.yingpai.fitness.dvp_2_0.main.util.CountDownTimer;
import com.yingpai.fitness.dvp_2_0.main.util.Util;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.dvp_2_0.main.widget.GlideImageLoader;
import com.yingpai.fitness.entity.HomeHotSelectedBean;
import com.yingpai.fitness.entity.UpdateStepBean;
import com.yingpai.fitness.entity.wx.TokenBean;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 精选栏目fragment
 */
public class FitnessFineChoosedFragment extends CommonFragment implements OnRefreshListener {

    private Unbinder unbinder;
    private TokenBean token;
    @BindView(R.id.hot_child_banner)
    Banner hot_child_banner;
    @BindView(R.id.home_strategy_gv)
    XGridView home_strategy_gv;
    @BindView(R.id.home_topic_lv)
    XListView home_topic_lv;
    @BindView(R.id.scrollview)
    NestedScrollView nestedScrollView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.title_bar)
    RelativeLayout title_bar;
    @BindView(R.id.empty)
    LinearLayout empty;
    @BindView(R.id.countStepLayout)
    LinearLayout countStepLayout;

    @BindView(R.id.todayStep)
    TextView todayStep;
    @BindView(R.id.shouyi)
    TextView shouyi;
    @BindView(R.id.xiaohao)
    TextView xiaohao;
    /**
     * 广告数据集合
     */
    private List<String> bannerList = new ArrayList<>();
    private QuickAdapter<HomeHotSelectedBean.MapBean.MiddleBanner> middleAdapter;
    private QuickAdapter<HomeHotSelectedBean.MapBean.DownBannersBean> bottomAdapter;
    private SensorEventListener sensorEventListener;
    private  long stepNum = 0l;

    private CountDownTimer timer;
    private boolean isFirst = true;

    public static FitnessFineChoosedFragment getInstance() {
        FitnessFineChoosedFragment fineChoosedFragment = new FitnessFineChoosedFragment();
        return fineChoosedFragment;
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dvp_2_0_finechoose, container, false);
        unbinder = ButterKnife.bind(this, view);
        title_bar.setVisibility(View.GONE);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));
        refreshLayout.setOnRefreshListener(this);

        token = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);

        //设置广告指示器
        hot_child_banner.setIndicatorGravity(BannerConfig.CENTER);
        middleAdapter = new QuickAdapter<HomeHotSelectedBean.MapBean.MiddleBanner>(context, R.layout.home_strategy_list_item) {
            @Override
            protected void convert(BaseAdapterHelper helper, HomeHotSelectedBean.MapBean.MiddleBanner item) {
                ImageView home_strategy_iv = helper.getView(R.id.home_strategy_iv);
                Glide.with(context).load(item.getPhotoUrl()).error(R.mipmap.default_small_bg).into(home_strategy_iv);
            }
        };
        home_strategy_gv.setAdapter(middleAdapter);

        home_strategy_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putString("linkurl",middleAdapter.getItem(position).getLinkUrl());
                startActivity(FitnessStrategyActivity.class,bundle);
            }
        });

        bottomAdapter = new QuickAdapter<HomeHotSelectedBean.MapBean.DownBannersBean>
                (context, R.layout.home_hot_selected_topic_list_item) {
            @Override
            protected void convert(BaseAdapterHelper helper, HomeHotSelectedBean.MapBean.DownBannersBean item) {
                ImageView home_strategy_iv = helper.getView(R.id.home_hot_selected_topic_item_iv);
                Glide.with(context).load(item.getPhotoUrl()).error(R.mipmap.default_small_bg).into(home_strategy_iv);
            }
        };
        home_topic_lv.setAdapter(bottomAdapter);

        home_topic_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putString("flag","home");
                bundle.putString("linkurl",bottomAdapter.getItem(position).getLinkUrl());
                startActivity(RunRideTopicDetailActivity.class,bundle);
            }
        });

        nestedScrollView.smoothScrollTo(0, 0);
        home_strategy_gv.setFocusable(false);
        home_topic_lv.setFocusable(false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        sensorEventListener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                Logger.e("步数：" + event.values[0] + "==" + event.timestamp);
                stepNum = (long) event.values[0];
                if(isFirst){
                    postData(stepNum);
                    isFirst = false;
                }
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
                Logger.e(sensor.getName() + "==" + accuracy);
            }
        };
        //SDK大于等于19，开启计步传感器，小于开启加速度传感器
        //int versionCodes  = Build.VERSION.SDK_INT;
        if(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_SENSOR_STEP_COUNTER)){ //
            SensorManager sensorManager= (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
            Sensor stepCounter = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
            sensorManager.registerListener(sensorEventListener, stepCounter, SensorManager.SENSOR_DELAY_FASTEST);
        }

        timer = new CountDownTimer(10000,1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }
            @Override
            public void onFinish() {
                this.start();
                postData(stepNum);
            }
        }.start();
    }

    /**
     * 上传步数
     * @param value 步数
     */
    private void postData(long value){
        Logger.e("ss","发送步数="+value);
        //showToast("发送步数="+value);
        HashMap<String,Object> map = new HashMap<>();
        map.put("stepCount",(long)value);
        map.put("type","1");
        //  try {
        map.put("phoneCode",Util.getUniquePsuedoID());
        //} catch (Exception e) {
        //    e.printStackTrace();
        //}
        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.SAVESTEPCOUNT,
                map, Url.SAVESTEPCOUNT, new Callback<UpdateStepBean>() {
                    @Override
                    public void onSuccess(UpdateStepBean bean) {
                        if(bean.getCode().equals("0")){
                            todayStep.setText(bean.getData().getStepCount()+"");
                            shouyi.setText(bean.getData().getPonit()+"");
                            xiaohao.setText(bean.getData().getCalorie()+"");
                        }
                    }

                    @Override
                    public void onError(Response response) {
                        super.onError(response);
                    }
                });
    }

    @Override
    @OnClick({R.id.homePlayLl, R.id.home_course_ll,R.id.empty,R.id.countStepLayout})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.homePlayLl:
                startActivity(RecreationActivity.class);
                break;
            case R.id.home_course_ll:
                startActivity(StoreActivity.class);
                break;
            case R.id.empty:
                onRefresh(refreshLayout);
                break;
            case R.id.countStepLayout:
                startActivity(StepDetailActivity.class);
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        hot_child_banner.startAutoPlay();
        if(null != timer)
            timer.start();

    }

    @Override
    public void onPause() {
        super.onPause();
        hot_child_banner.stopAutoPlay();
        if(null != timer)
            timer.cancel();

    }

    @Override
    protected void initData() {
        HttpParams httpParams = new HttpParams();
        httpParams.put("customerId", token.getId());
        httpParams.put("tagId", Constant.NUM_1);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.FITNESS_FRAGMENT_DATA, httpParams, Url.FITNESS_FRAGMENT_DATA,
                new Callback<HomeHotSelectedBean>() {
                    @Override
                    public void onSuccess(final HomeHotSelectedBean bean) {
                        if(bean.getResult().equals(Constant.REQUEST_SUCCESS)){
                            empty.setVisibility(View.GONE);
                            bannerList.clear();
                            /**
                             * 将数据对应为广告的数据
                             */
                            for (int i = 0; i < bean.getMap().getUpBanners().size(); i++) {
                                bannerList.add(bean.getMap().getUpBanners().get(i).getPhotoUrl());
                            }

                            hot_child_banner.setOnBannerListener(new OnBannerListener() {
                                @Override
                                public void OnBannerClick(int position) {
                                    if (bean.getMap().getUpBanners().get(position).getLinkUrl() != null &&
                                            !TextUtils.isEmpty(bean.getMap().getUpBanners().get(position).getLinkUrl())) {
                                        String linkUrl = bean.getMap().getUpBanners().get(position).getLinkUrl();
                                        if (bean.getMap().getUpBanners().get(position).getLinkUrl().equals("vipCard")) {
                                            startActivity(VipCardActivity.class);
                                        }else if(bean.getMap().getUpBanners().get(position).getLinkUrl().startsWith("link@")){
                                            String url = linkUrl.substring(linkUrl.indexOf("@")+1, linkUrl.indexOf(","));
                                            String title = linkUrl.substring(linkUrl.indexOf(",")+1, linkUrl.length());
                                            Bundle bundle = new Bundle();
                                            bundle.putString("bannerLink_title", url);
                                            bundle.putString("bannerLink_url",title);
                                            startActivity(WebViewForBannerActivity.class,bundle);
                                        }
                                    }
                                }
                            });
                            hot_child_banner.setImages(bannerList)
                                    .setDelayTime(3000)
                                    .setImageLoader(new GlideImageLoader())
                                    .start();
                            /**
                             * 健身攻略
                             */
                            List<HomeHotSelectedBean.MapBean.MiddleBanner> middleBanners = bean.getMap().getMiddleBanners();
                            middleAdapter.clear();
                            middleAdapter.addAll(middleBanners);
                            /**
                             * 最下面的精选话题
                             */
                            List<HomeHotSelectedBean.MapBean.DownBannersBean> downBanners = bean.getMap().getDownBanners();
                            bottomAdapter.clear();
                            bottomAdapter.addAll(downBanners);
                        }else{
                            empty.setVisibility(View.VISIBLE);
                            showToast(bean.getMsg());
                        }
                        refreshLayout.finishRefresh();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        empty.setVisibility(View.VISIBLE);
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        initData();
        postData(stepNum);
    }

}
